<template>
  <div v-loading="loading">
    <BasicTable @register="registerTable" :rowSelection="rowSelection">

      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd"> 新增</a-button>
        <a-dropdown v-if="getSelectRowKeys().length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="i-ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="i-mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
    </BasicTable>
    <AddForm @register="registerAddForm" @success="handleEdit" />
  </div>
</template>

<script lang="ts" name="system-user" setup>
  //ts语法
  import { ref, computed, unref } from "vue"
  import { BasicTable, TableAction, ActionItem, useTable, BasicColumn } from "/@/components/Table"
  import { useDrawer } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import AddForm from "./Add.vue"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { columns, searchFormSchema, AppTypeEnum } from "./data"
  import { batchDeleteUser, frozenBatch } from "/@/api/member/user.api"
  import * as tenantApi from "/@/api/iam/tenant"
  import * as appApi from "/@/api/iam/app"
  import { Icon } from "/@/components/Icon"
  import { useGo } from "/@/hooks/web/usePage"
  import { updateApp } from "/@/api/iam/tenant";
  import { Modal } from "ant-design-vue";
  import { openWindow } from "/@/utils"
  import { useIam } from '/@/hooks/web/useIam'
  // import { usePermission } from '/@/hooks/web/usePermission'
  // const { hasPermission } = usePermission();
  const [registerAddForm, { openModal: openAddForm }] = useModal()
  const { createMessage, createConfirm } = useMessage()
  const go = useGo()
  const selectRows = ref([])
  const loading = ref(false)
  const actionColumn: BasicColumn = {
    width: 200,
    title: "操作",
    dataIndex: "action",
    fixed: "right",
    slot: "tableActions",
    dropDownActions: (record) => [
      {
        label: "下线",
        ifShow: record.appType == AppTypeEnum.CUSTOM && record.appStatus == 2,
        color: "error",
        // auth: 'sys:area:updateStatus',
        popConfirm: {
          title: "确定下线吗?",
          confirm: handleOfflineApp.bind(null, record.appId),
        },
      },
      {
        label: "上线",
        // auth: 'sys:area:updateStatus',
        ifShow: record.appType == AppTypeEnum.CUSTOM,
        popConfirm: {
          title: "确定启用吗?",
          confirm: handleDeployApp.bind(null, record.appId),
        },
      },
      {
        label: "编辑",
        // auth: 'sys:area:update',
        onClick: handleEdit.bind(null, record.appId),
      }
    ],
    actions: (record) => [
      {
        label: "进入",
        ifShow: !!record.homePageUrl,
        // auth: 'sys:area:delete',
        onClick: handleJumpAppUrl.bind(null, record)
      },
      {
        label: "卸载",
        color: "error",
        ifShow: record.canDelete,
        // auth: 'sys:area:delete',
        onClick: handleUninstallApp.bind(null, record)
      },
      {
        label: "禁用",
        ifShow: record.tenantAppStatus == 1,
        color: "error",
        // auth: 'sys:area:updateStatus',
        popConfirm: {
          title: "确定禁用吗?",
          confirm: handleUpdateStatus.bind(null, record.appId, "2"),
        },
      },
      {
        label: "启用",
        ifShow: record.tenantAppStatus == 2,
        // auth: 'sys:area:updateStatus',
        popConfirm: {
          title: "确定启用吗?",
          confirm: handleUpdateStatus.bind(null, record.appId, "1"),
        },
      }
    ]
  }

  const [registerTable, { reload, updateTableDataRecord, rowSelection, getSelectRowKeys }] = useTable({
    title: "应用列表",
    api: tenantApi.pageApp,
    bordered: false,
    columns: columns,
    size: "small",
    formConfig: {
      baseColProps: { lg: 6, md: 12 },
      labelWidth: 80,
      schemas: searchFormSchema,
      showResetButton: false,
    },
    actionColumn,
    showTableSetting: true,
    useSearchForm: true,
    pagination: true,
    canResize: true,
    rowKey: "id",
    beforeFetch: (params) => {
      return Object.assign({ column: "createTime", order: "desc" }, params)
    },
  })

  const handleUpdateStatus = async (appId, status) => {
    await updateApp({ appId, status })
    createMessage.success("更新成功")
    await reload()
  }

  const handleOfflineApp = async (appId) => {
    try {
      loading.value = true
      await appApi.offlineApp({ appId })
      createMessage.success("下线成功")
      await reload()
    } finally {
      loading.value = false
    }
  }

  const handleDeployApp = async (appId) => {
    try {
      loading.value = true
      await appApi.deployApp({ appId })
      createMessage.success("上线成功")
      await reload()
    } finally {
      loading.value = false
    }

  }

  function handleEdit( appId ) {
    go('/console/myApp/edit/' + appId)
  }

  const handleJumpAppUrl = (record) => {
    const tenantId = useIam().getTenantId()
    openWindow(`${record.homePageUrl}?appId=${record.appId}&tenantId=${tenantId}`, { target: '_blank' })
  }

  const handleAdd = () => {
    openAddForm(true, {})
  }

  async function handleUninstallApp(record) {
    Modal.confirm({
      title: "确认卸载",
      content: "是否卸载选中应用，不可恢复",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        await tenantApi.uninstallApp({ appId: record.appId })
        await reload()
      },
    })

  }

  async function batchHandleDelete() {
    let hasAdmin = unref(selectRows).filter((item) => item.isAdmin)
    if (unref(hasAdmin).length > 0) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await batchDeleteUser({ ids: getSelectRowKeys() }, () => {
      // selectedRowKeys.value = []
      reload()
    })
  }

</script>

<style scoped></style>
